/**
 * React弹幕组件
 * 提供React集成的弹幕功能
 */

import { useRef, useEffect, useImperativeHandle, forwardRef } from 'react'
import { BarrageRenderer } from './BarrageRenderer'
import type { VideoBarrageProps, BarrageAPI, BarrageItem } from '../types'
import { getPreset } from '../types/presets'

export const VideoBarrage = forwardRef<BarrageAPI, VideoBarrageProps>(
  ({ videoRef, config, events, initialBarrages, enabled = true, children }, ref) => {
    const containerRef = useRef<HTMLDivElement>(null)
    const rendererRef = useRef<BarrageRenderer | null>(null)

    // 暴露API给父组件
    useImperativeHandle(ref, () => ({
      add: (barrage: Omit<BarrageItem, 'id'>) => {
        if (!rendererRef.current) return ''
        return rendererRef.current.add(barrage)
      },
      remove: (id: string) => {
        if (!rendererRef.current) return false
        return rendererRef.current.remove(id)
      },
      clear: () => {
        rendererRef.current?.clear()
      },
      pause: () => {
        rendererRef.current?.pause()
      },
      resume: () => {
        rendererRef.current?.resume()
      },
      getActiveCount: () => {
        return rendererRef.current?.getActiveCount() || 0
      },
      getMaxCapacity: () => {
        return rendererRef.current?.getMaxCapacity() || 0
      },
      updateConfig: (newConfig) => {
        rendererRef.current?.updateConfig(newConfig)
      },
      destroy: () => {
        rendererRef.current?.destroy()
      }
    }), [])

    // 初始化渲染器
    useEffect(() => {
      if (!containerRef.current) return

      try {
        const renderer = new BarrageRenderer({
          container: containerRef.current,
          video: videoRef?.current || undefined,
          config: config || getPreset('default'),
          events
        })

        rendererRef.current = renderer

        // 添加初始弹幕
        if (initialBarrages) {
          initialBarrages.forEach(barrage => {
            renderer.add(barrage)
          })
        }

        return () => {
          renderer.destroy()
          rendererRef.current = null
        }
      } catch (error) {
        console.error('弹幕渲染器初始化失败:', error)
        events?.onError?.(error as Error)
      }
    }, [videoRef, config, events, initialBarrages])

    // 启用/禁用控制
    useEffect(() => {
      if (!rendererRef.current) return

      if (enabled) {
        rendererRef.current.resume()
      } else {
        rendererRef.current.pause()
      }
    }, [enabled])

    return (
      <div
        ref={containerRef}
        className="video-barrage-container"
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          width: '100%',
          height: '100%',
          pointerEvents: 'none',
          overflow: 'hidden'
        }}
      >
        {children}
      </div>
    )
  }
)

VideoBarrage.displayName = 'VideoBarrage'

export default VideoBarrage
